package com.gree.shyun.server.gupiao.service;

import com.gree.shyun.bean.*;
import com.alibaba.fastjson.JSON;
import com.gree.shyun.server.db.DbHelper;
import com.gree.shyun.server.db.sqlite.Selector;
import com.gree.shyun.server.db.util.LogUtils;
import com.gree.shyun.server.gupiao.bean.GuPiaoMessage;
import com.gree.shyun.server.taskpool.async.bean.Result;
import com.gree.shyun.util.json.JsonMananger;

import java.util.ArrayList;
import java.util.List;

public class GuPiaoService {
    public Result handle(String method,Object data,String resRoot ){
        System.out.println(method);
        switch (method){
            case "getMessage":
                List<GuPiaoMessage> messages = DbHelper.findAll(Selector.from(GuPiaoMessage.class));
                return success(method,messages);
            case "insertMessage":
                List<GuPiaoMessage> list = new ArrayList<>();
                for(int i = 0 ; i < 1000;i++){
                    GuPiaoMessage guPiaoMessage = new GuPiaoMessage();
                    guPiaoMessage.setDate("2022-02-15");
                    guPiaoMessage.setTime("17:37");
                    guPiaoMessage.setImportance("重要");
                    guPiaoMessage.setMessage("iu上的覅u会很高的时间覅，上的覅第四u回公司的，上的覅就告诉对方，轨迹回放给对方，的风格，的风格， 的发挥顺丰大概的风格的风格回到法国，给的符号的风格的风格好地方，地方，广泛的回到法国的方法很多风格的回复好的和，东方红东方红他的风格然后的风格，的风格的，复活点复活电话发给地方，给的，发给的活动复活点复活的，发给的风格和豆腐干地方，好好奋斗刚认识的给，的复合体划分给对方。");
                    guPiaoMessage.setType("测试");
                    list.add(guPiaoMessage);
                }
                DbHelper.save(list);
                return success(method,"ok");
        }
        return error(method,-1,"方法未定义");
    }

    /**
     *  返回成功消息
     * @param method
     * @param result
     * @return
     */
    public static Result success(String method,Object result){
        method = "gupiao_"+method;
        Message message = new Message();
        message.setCode(200);
        message.setMessage("执行成功!");
        String json;
        if(result instanceof String){
            String res = result.toString();
            res = res.replaceAll("\r|\n", "");
            message.setData(res);
        }else{
            message.setData(result);
        }
        json = JSON.toJSON(message).toString();
        //文件路径处理 把 \\ 转 /
        json = json.replaceAll("\\\\\\\\","/");
        LogUtils.e(method+":"+json);
        json = json.replaceAll("\\\"","\\\\\\\"");
       return Result.put(method).put("result",json);
    }

    /**
     * 返回失败消息
     * @param method
     * @param code
     * @param msg
     * @return
     */
    public static Result error(String method,int code,String msg){
        method = "gupiao_"+method;
        Message message = new Message();
        message.setCode(code);
        message.setMessage(msg);
        String json = JsonMananger.beanToJsonStr(message);
        LogUtils.e(json);
        return  Result.put(method).put("result",json);
    }
}
